import { IAsynHandler, AsynCallback, AnyCallback,AnyCallback1 } from "../bean";

export default class AsynHandler implements IAsynHandler {
  _data: any = null;
  _listenList: (typeof AsynCallback)[] | null = null;

  // 获取函数：回传key属性对应的值
  register(key: string): typeof AnyCallback1 {
    if (!this._data) {
      this._data = {};
    }
    if (Object.keys(this._data).indexOf(key) == -1) {
      this._data[key] = undefined;
    }
    let self = this;
    return function (success, data) {
      self._data[key] = (success && data !== undefined) ? data : null;
      if (self.checkData()) {// 处理已提交的申请
        if (self._listenList) {
          self._listenList.forEach(callback => {
            callback(self._data);
          });
          self._listenList = null;
        }
      }
    };
  }

  // 获取：多个key属性对应的值组成的对象
  getData(callback: typeof AsynCallback): void {
    if (!callback) {
      return;
    }
    if (this.checkData()) {
      callback(this._data);
    } else {
      if (!this._listenList) {
        this._listenList = [];
      }
      this._listenList.push(callback);
    }
  }

  // 检查对象是否获取完整
  checkData(): boolean {
    if (!this._data) {
      return false;
    }
    for (let key in this._data) {
      if (this._data[key] === undefined) {
        return false;
      }
    }
    return true;
  }
}